package com.hexb.core.utils;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Package : com.hexb.cms.core.utils
 * @Author : hexb
 * @Date : 2018-08-5 15:31
 * 提供Http文件下载或图片文件引用
 */
@Slf4j
public class HttpFileUtils {

    public static void writeFileWithResponse(String filePath, HttpServletResponse response, boolean attachment) throws IOException {
        File file = new File(filePath);
        writeFileWithResponse(file, response, attachment);
    }

    public static void writeFileWithResponse(File file, HttpServletResponse response, boolean attachment) throws IOException {
        writeFileWithResponse(file, response, attachment, () -> {
            Pattern p = Pattern.compile(".*/((.*?)\\.(.*))");
            Matcher matcher = p.matcher(file.getAbsolutePath());
            if (matcher.find()) {
                return matcher.group(1);
            }
            return UUID.randomUUID().toString();
        });
    }

    public static void writeFileWithResponse(String filePath, HttpServletResponse response, boolean attachment, Supplier<String> fileNameSupplier) throws IOException {
        writeFileWithResponse(new File(filePath), response, attachment, fileNameSupplier);
    }

    /**
     * @param attachment 是否是附件
     */
    public static void writeFileWithResponse(File file, HttpServletResponse response, boolean attachment, Supplier<String> fileNameSupplier) throws IOException {
        if (!file.exists()) {
            throw new RuntimeException("File [ " + file.getAbsolutePath() + " ] Not Exists!");
        }

        InputStream ins = new FileInputStream(file);
        writeFileWithResponse(ins, response, attachment, fileNameSupplier);
    }

    /**
     * @param attachment 是否是附件
     */
    public static void writeFileWithResponse(InputStream ins, HttpServletResponse response, boolean attachment, Supplier<String> fileNameSupplier) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        if (attachment) {
            String fileName = fileNameSupplier == null ? UUID.randomUUID().toString() : fileNameSupplier.get();
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
        }
        OutputStream ous = response.getOutputStream();
        writeStream(ins, ous, true);
    }


    public static void writeStream(InputStream ins, OutputStream ous, boolean autoClose) throws IOException {
        if (ins == null) return;
        try {
            byte[] b = new byte[2048];
            int length;
            while ((length = ins.read(b)) > 0) {
                ous.write(b, 0, length);
            }
            ous.flush();
        } finally {
            if (autoClose) {
                try {
                    if (ins != null) ins.close();
                    if (ous != null) ous.close();
                } catch (IOException e) {
                    log.error("close Stream Error!", e);
                }
            }
        }
    }
}
